<script lang="ts">
import {useRouter, useRoute} from 'vue-router';
import Bus from '@likg/bus';
import Validator from '@likg/validator';
import {showToast, showLoadingToast, closeToast} from 'vant';
import {api, apiCommon} from "@/api/apiServer";
import wxFn from "@/utils/wxFn";
import {useUserStore} from "@/stores/modules/user";
import {aes_encrypt} from "@/utils/aes_endecrypt.js";

import {
    defineComponent,
    onUnmounted,
    reactive,
    toRefs,
    watch,
    ref,
    onMounted,
    watchEffect,
} from 'vue';
import Vcode from "vue3-puzzle-vcode";
import img1 from '@/assets/images/01.jpg';
import img2 from '@/assets/images/02.jpg';
import img3 from '@/assets/images/03.jpg';
import img4 from '@/assets/images/04.jpg';
import img5 from '@/assets/images/05.jpg';
import img6 from '@/assets/images/06.jpg';
import img7 from '@/assets/images/07.jpg';


interface StateProps {
    phone: string;
    realName: string;
    code: string;
    countdown: number;
    bounding: number;
    timer: any;
    canSendCode: boolean;
    canBind: boolean;
    isShow: boolean,
    showJihuoDialog: boolean,
    jihuoType: any[],
    imgs: string[];
    currJihuoActive: string
}

export default defineComponent({
    components: {Vcode},
    setup() {
        const store = useUserStore();
        const router = useRouter();
        const route = useRoute();

        const state = reactive<StateProps>({
            phone: '',
            code: '',
            realName: '',
            countdown: 60,
            bounding: 60,
            timer: null,
            canSendCode: false,
            canBind: false,
            isShow: false,
            showJihuoDialog: false,
            currJihuoActive: "1",
            jihuoType: [
                {
                    id: "1",
                    name: '卡密激活'
                },
                {
                    id: "2",
                    name: '验证激活'
                }
            ],
            imgs: [
                img1,
                img2,
                img3,
                img4,
                img5,
                img6,
                img7,
            ],
        });
        // events
        const onSendMsg = () => {
            if (!state.canSendCode) {
                return;
            }
            state.isShow = true;
        };
        const onBind = async () => {
            if (!state.canBind) {
                return;
            }
            showLoadingToast({
                message: '正在绑定...',
                forbidClick: true
            });

            // 创建用户
             let res:any = await api.createUser({
                userHeadImage: wxRestInfo.value.headimgurl,
                verifyCode:state.code||'',
                nickName: wxRestInfo.value.nickname||'',
                openId: wxRestInfo.value.openid||'',
                channelId: localStorage.getItem('channelId') || '',
                phoneNumber: state.phone||'',
                realName: state.realName||''
              });

            // 根据openid 验证用户是否激活
            closeToast();
            if (res.code === 200) {
                store.setUserId(res.data);
                checkUserActiveFn(wxRestInfo.value.openid)
            } else {
                showToast({
                    message: res.msg,
                    icon: 'none'
                })
            }
        };
        // watch
        watchEffect(() => {
            if (!Validator.isTel(state.phone) || state.code.length <= 0) {
                state.canBind = false;
            } else {
                state.canBind = true;
            }
        });
        watch(
            () => state.phone,
            (phone) => {
                state.canSendCode = Validator.isTel(phone);
            }
        );
        // life circles
        onUnmounted(() => {
            clearInterval(state.timer);
            state.timer = null;
        });

        // 滑动验证组件

        const onSuccess = async () => {
            // --- 调用接口获取短信验证码
            showLoadingToast({
                message: '正在发送...',
                forbidClick: true,
                duration: 20 * 1000,
            });

            let res: any = await apiCommon.sendCode({mobile: aes_encrypt(state.phone)});
            if (res.code === 200) {
                state.isShow = false;
                // state.code = res.data;

                closeToast();
                state.timer = setInterval(() => {
                    if (state.countdown === 1) {
                        state.countdown = state.bounding;
                        clearInterval(state.timer);
                    } else {
                        state.countdown -= 1;
                    }
                }, 1000);
            }

        }
        const onFail = (e) => {
            console.log(e);
        }

        const linkToJihuofn = () => {
            // 关闭弹框
            state.showJihuoDialog = false
            router.push(`/login/bindCar?type=${state.currJihuoActive}`)
        }
        const activeJihuoTypeFn = (item: any) => {
            state.currJihuoActive = item.id
        }

        // 根据openid 验证用户是否激活
        const checkUserActiveFn = async (openId: string) => {
            // 清除token
            await apiCommon.clearToken()
            let res: any = await api.checkUserIsActive({
                openId
            });
            if (res.code === 200) {
                localStorage.removeItem("token");
                localStorage.removeItem("customerId");
                // 用户已创建已激活
                // 保存token
                localStorage.setItem("token", res.data.token.token);
                localStorage.setItem("customerId", res.data.customerId);
                store.setUserId(res.data.customerId);
                store.setToken(res.data.token.token);
                router.replace("/");
            }
        }


        // 获取wx code 信息
        const wxRestInfo = ref()
        const getWxCodeInfo = async () => {
            let res: any = await wxFn.checkToken();
            if (res.code === 200) {
                wxRestInfo.value = res.data
                let {openid} = res.data
                // 保存openid
                store.setWxOpenId(openid)
                // 根据openid 验证用户是否激活
                checkUserActiveFn(openid)
            } else {
                showToast({
                    message: res.msg,
                    icon: 'none'
                })
            }
        }
        onMounted(() => {
             checkUserActiveFn("oHi2ivscTbVlTgmTo2ztmhNABDbk")
            //getWxCodeInfo();
        })

        return {
            ...toRefs(state),
            onSendMsg,
            onBind,
            onSuccess,
            onFail,
            linkToJihuofn,
            activeJihuoTypeFn
        };
    },
});
</script>

<template>
    <div class="bind-phone">
        <div class="mt-46">
            <van-field
                v-model="phone"
                label-width="60"
                label="手机号"
                type="tel"
                maxlength="11"
                clearable
                placeholder="请输入手机号码"
                :border="false"
            />
            <van-field
                v-model="realName"
                label-width="60"
                label="姓名"
                type="text"
                clearable
                placeholder="请输入姓名"
                :border="false"
            />
            <van-field
                v-model="code"
                type="digit"
                label-width="60"
                label="验证码"
                maxlength="6"
                clearable
                placeholder="请输入验证码"
                :border="false"
            >
                <template #button>
                    <div class="valcode"
                         v-if="countdown === bounding"
                         @click="onSendMsg"
                         :style="{ color: canSendCode ? '#F59A23' : '#FBD3A1' }"
                    >
                        发送验证码
                    </div>
                    <div class="valcode" v-else style="color: #fbd3a1">{{ countdown }}S后重新获取</div>
                </template>
            </van-field>
            <!--            <van-field-->
            <!--                style="background-color:#11ffee00;"-->
            <!--                readonly-->
            <!--                input-align="right"-->
            <!--            >-->
            <!--                <template #button>-->
            <!--                    <div class="valcode"-->
            <!--                         v-if="countdown === bounding"-->
            <!--                         @click="onSendMsg"-->
            <!--                         :style="{ color: canSendCode ? '#F59A23' : '#FBD3A1' }"-->
            <!--                    >-->
            <!--                        发送验证码-->
            <!--                    </div>-->
            <!--                    <div class="valcode" v-else style="color: #fbd3a1">{{ countdown }}S后重新获取</div>-->
            <!--                </template>-->
            <!--            </van-field>-->
        </div>
        <div class="bind-btn" :class="{ can: canBind }" @click="onBind">
            登录
        </div>

        <Vcode :imgs="imgs" :show="isShow" @success="onSuccess" @fail="onFail"/>


        <!-- 选择激活方式 -->
        <van-dialog v-model:show="showJihuoDialog" title="确认激活方式" :showConfirmButton="false">
            <div class="flex-v-center mt-30">
                <div class="flex justify-center">
                    <van-button style="margin: 0 10px;" :color="currJihuoActive===item.id?'#7232dd':''"
                                @click="activeJihuoTypeFn(item)" v-for="item in jihuoType" :key="item.id" plain>
                        {{ item.name }}
                    </van-button>
                </div>

                <div class="pt-40 pb-29 flex-h-between">
                    <van-button round color="#F59A23"
                                style="height: 50px; width:110px;" @click="linkToJihuofn">确定
                    </van-button>
                </div>
            </div>
        </van-dialog>

    </div>
</template>

<style lang="less" scoped>
//.valcode {
//    background-color: white;
//    border-radius: 10px;
//    height: 50px;
//    width: 80px;
//    line-height: 50px;
//    margin-top: -11px;
//    margin-right: -18px;
//    text-align: center;
//    vertical-align: middle;
//}

.bind-phone {
    // height: 100vh;
    border-radius: 30px;
    padding: 50px 30px 80px;
}

.logo {
    width: 100px;
    height: 100px;
    display: block;
    margin: 0 auto;
}

:deep(.van-field) {
    height: 44px;
    margin-bottom: 20px;
    background-color: #ffffff;
    display: flex;
    align-items: center;
    color: red;
}

.code-button {
    font-size: 14px;
    font-weight: 400;
    color: #fbd3a1;
    line-height: 14px;
}

.bind-btn {
    margin-top: 40px;
    height: 44px;
    background: #F59A23;
    color: #fff;
    border-radius: 22px;

    display: flex;
    justify-content: center;
    align-items: center;

    font-size: 16px;
    font-weight: 500;
    opacity: 0.5;

    &.can {
        opacity: 1;
    }
}
</style>
